package com.ityj.yygh.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ityj.yygh.enums.AuthStatusEnum;
import com.ityj.yygh.helper.JwtHelper;
import com.ityj.yygh.model.user.Patient;
import com.ityj.yygh.model.user.UserInfo;
import com.ityj.yygh.user.mapper.UserInfoMapper;
import com.ityj.yygh.user.service.PatientService;
import com.ityj.yygh.user.service.UserInfoService;
import com.ityj.yygh.vo.user.LoginVo;
import com.ityj.yygh.vo.user.UserInfoQueryVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PatientService patientService;

    @Override
    public Map<String, Object> loginWithPhone(LoginVo loginVo) {
        Map<String, Object> result = new HashMap<>();

        // 首先判断页面输入的验证码和后台手机生成的是否一致
        String phoneNumber = loginVo.getPhone();
        String codeFromUser = loginVo.getCode();

        if (StringUtils.isAnyEmpty(phoneNumber, codeFromUser)) {
            log.warn("Please check your input parameters!");
            return result;
        }

        // 校验验证码
        String redisCode = (String) redisTemplate.opsForValue().get(phoneNumber);
        if (StringUtils.isEmpty(redisCode)) {
            log.warn("验证码已过期！");
            return result;
        }
        if (!codeFromUser.equals(redisCode)) {
            log.warn("验证码输入错误，请重试！");
            return result;
        }

        // 判断当前手机号是否为新用户
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phoneNumber);
        UserInfo userInfo = baseMapper.selectOne(queryWrapper);
        if (userInfo == null) {
            log.info("This phone has not registered!");
            userInfo = new UserInfo();
            userInfo.setPhone(phoneNumber);
            userInfo.setStatus(1);
            userInfo.setName("");
            baseMapper.insert(userInfo);
        }

        // 返回页面显示名称
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        // 通过JWT(jSON WEB TOKEN) 生成token码记录登录信息
        String token = JwtHelper.createToken(userInfo.getId(), name);
        result.put("name", name);
        result.put("token", token);
        return result;
    }

    @Override
    public IPage<UserInfo> searchUserInfoByCondition(UserInfoQueryVo userInfoQueryVo, Page<UserInfo> pageParam) {
        String name = userInfoQueryVo.getKeyword();   // 用户名称 关键字
        Integer status = userInfoQueryVo.getStatus();
        Integer authStatus = userInfoQueryVo.getAuthStatus();
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(name)) {
            queryWrapper.like("name", name);
        }
        if (status != null) {
            queryWrapper.like("status", status);
        }
        if (authStatus != null) {
            queryWrapper.like("auth_status", authStatus);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            queryWrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            queryWrapper.le("create_time",createTimeEnd);
        }

        IPage<UserInfo> userInfoPage = baseMapper.selectPage(pageParam, queryWrapper);
        userInfoPage.getRecords().forEach(this::packageUserInfo);
        return userInfoPage;
    }

    @Override
    public void updateStatus(Long userId, Integer status) {
        // 0锁定 1正常
        if(status == 0 || status == 1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setStatus(status);
            baseMapper.updateById(userInfo);
        }
    }

    @Override
    public Map<String, Object> getUserDetail(Long userId) {
        Map<String, Object> result = new HashMap<>();
        // 用户信息
        UserInfo userInfo = baseMapper.selectById(userId);
        this.packageUserInfo(userInfo);
        result.put("userInfo", userInfo);

        // 就诊人信息
        List<Patient> patientList = patientService.findAll(userId);
        result.put("patientList", patientList);
        return result;
    }

    // 用户审核功能
    @Override
    public void approve(Long userId, Integer authStatus) {
        // 0：未认证 1：认证中 2：认证成功 -1：认证失败
        UserInfo userInfo = baseMapper.selectById(userId);
        if (userInfo == null) {
            log.warn("当前用户不存在");
            return;
        }
        if (userInfo.getAuthStatus() != 1) {
            log.info("只能对认证中的用户进行审核");
            return;
        }
        userInfo.setAuthStatus(authStatus);
        baseMapper.updateById(userInfo);
    }

    //编号变成对应值封装
    private void packageUserInfo(UserInfo userInfo) {
        //处理认证状态编码
        userInfo.getParam().put("authStatusString", AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态 0  1
        String statusString = userInfo.getStatus() == 0 ? "锁定" : "正常";
        userInfo.getParam().put("statusString", statusString);
    }

}

